package com.ruoyi.resume.service.impl;

import com.ruoyi.resume.domain.model.*;
import com.ruoyi.resume.domain.model.Category;
import com.ruoyi.resume.enums.TaskType;
import com.ruoyi.resume.mapper.CategoryMapper;
import com.ruoyi.resume.mapper.ResumeTagMapper;
import com.ruoyi.resume.mapper.TagMapper;
import com.ruoyi.resume.service.TagService;
import com.ruoyi.resume.task.Task;
import com.ruoyi.resume.task.TaskQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl implements TagService {

    private static final Logger logger = LoggerFactory.getLogger(TagServiceImpl.class);

    @Autowired
    private ResumeTagMapper resumeTagMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private TaskQueue taskQueue;

    @Override
    public Map<String, Integer> getTagsByResumeId(Integer resumeId) {
        // 从数据库中获取 ResumeTag 列表
        List<ResumeTag> resumeTags = resumeTagMapper.selectResumeTagsByResumeId(resumeId);

        // 使用 Java Stream 将列表转换为 Map，其中 tagValue 为键，tagId 为值
        Map<String, Integer> tagValueToTagIdMap = resumeTags.stream()
                .collect(Collectors.toMap(ResumeTag::getTagValue, ResumeTag::getTagId));

        return tagValueToTagIdMap;
    }

    @Override
    public List<Category> getAllTags() {
        // 1. 查询所有分类和标签
        List<Category> categories = categoryMapper.selectAllCategories();
        List<Tag> tags = tagMapper.selectAllTags();

        // 如果分类或标签为空，返回空列表
        if (categories == null || categories.isEmpty()) {
            return Collections.emptyList();
        }
        if (tags == null) {
            tags = new ArrayList<>();
        }

        // 2. 创建标签映射：categoryId -> List<Tag>
        Map<Integer, List<Tag>> tagMap = createTagMap(tags);

        // 3. 构建分类树
        Map<Integer, Category> categoryMap = buildCategoryTree(categories);

        // 4. 将标签分配到最后一层分类
        assignTagsToLastLevelCategories(tagMap, categoryMap);

        // 5. 返回顶级分类列表（ParentId 为 null）
        return collectTopLevelCategories(categoryMap);
    }

    private Map<Integer, List<Tag>> createTagMap(List<Tag> tags) {
        Map<Integer, List<Tag>> tagMap = new HashMap<>();
        for (Tag tag : tags) {
            tagMap.computeIfAbsent(tag.getCategoryId(), k -> new ArrayList<>()).add(tag);
        }
        return tagMap;
    }

    private Map<Integer, Category> buildCategoryTree(List<Category> categories) {
        Map<Integer, Category> categoryMap = new LinkedHashMap<>();
        for (Category category : categories) {
            category.setChildren(new ArrayList<>()); // 初始化子分类列表
            category.setTags(new ArrayList<>());     // 初始化标签列表
            categoryMap.put(category.getId(), category);

            // 将当前分类挂到父分类的子分类列表中
            if (category.getParentId() != null && categoryMap.containsKey(category.getParentId())) {
                categoryMap.get(category.getParentId()).getChildren().add(category);
            }
        }
        return categoryMap;
    }

    private void assignTagsToLastLevelCategories(Map<Integer, List<Tag>> tagMap, Map<Integer, Category> categoryMap) {
        for (Map.Entry<Integer, List<Tag>> entry : tagMap.entrySet()) {
            Integer categoryId = entry.getKey();
            List<Tag> categoryTags = entry.getValue();

            if (categoryMap.containsKey(categoryId)) {
                Category category = categoryMap.get(categoryId);
                if (Boolean.TRUE.equals(category.getIsLastLevel())) { // 仅为最后一层设置标签
                    category.setTags(categoryTags);
                }
            } else {
                logger.warn("标签的 categoryId={} 没有对应的分类，跳过", categoryId);
            }
        }
    }

    private List<Category> collectTopLevelCategories(Map<Integer, Category> categoryMap) {
        List<Category> topLevelCategories = new ArrayList<>();
        for (Category category : categoryMap.values()) {
            if (category.getParentId() == null) {
                topLevelCategories.add(category);
            }
        }
        return topLevelCategories;
    }

    @Override
    public Integer createTag(Tag tag) {
        Integer maxId = tagMapper.getMaxId();
        Integer newId = maxId + 1; // 获取比最大id大1的值
        tag.setId(newId);
        tagMapper.insertTag(tag);
        return newId;
    }

    @Override
    public boolean deleteTagById(Integer id) {
        // 删除 resume_tag 表中关联的所有行
//        resumeTagMapper.deleteByTagId(id);
        taskQueue.addTask(new Task(TaskType.DELETE_TAG, id));

        // 删除 tag 表中对应的标签
        tagMapper.deleteTagById(id);

        return true;
    }


    @Override
    public boolean updateTag(Tag tag) {
        try {
            // 调用 Mapper 更新标签
            int rowsAffected = tagMapper.updateTag(tag);
            if (rowsAffected > 0) {
                taskQueue.addTask(new Task(TaskType.DELETE_TAG, tag.getId()));
                taskQueue.addTask(new Task(TaskType.UPDATE_TAG, tag.getId()));
                return true;
            }
            return false;
        } catch (Exception e) {
            // 打印日志s
            logger.error("Failed to update tag with id {}: {}", tag.getId(), e.getMessage(), e);
            return false;
        }
    }

    @Override
    public void deleteTagsByResumeId(int resumeId) {
        resumeTagMapper.deleteByResumeId(resumeId);
    }


}

